<template>
  <div class="user-management">
    <h2>欢迎，已登录管理员</h2>
    <button @click="goToLogin">返回登录页面</button>
    <table>
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>地址</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.name }}</td>
          <td>{{ user.age }}</td>
          <td>{{ user.address }}</td>
          <td>
            <button @click="editUser(user)">编辑</button>
            <button @click="confirmDeleteUser(user)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div>
      <h3>新增用户</h3>
      <input v-model="newUser.name" placeholder="姓名" />
      <input v-model="newUser.age" type="number" placeholder="年龄"/>
      <input v-model="newUser.address" placeholder="地址" />
      <button @click="addUser">添加用户</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      users: [
        {id:1,name:'张三',age:20,address:'上海'},
        {id:2,name:'李四',age:21,address:'北京'},
      ],
      newUser: {
        id: null,
        name: '',
        age: '',
        address: ''
      }
    };
  },
  methods: {
    goToLogin(){
      this.$router.push('/page1');
    },

    editUser(user){
      this.newUser = {...user};
    },
    addUser(user) {
      this.newUser.id = Date.now();
      this.users.push({...this.newUser});
      this.newUser = {id:null,name:'',age:'',address:''};
    },
    confirmDeleteUser(user) {
      if(confirm('确定要删除这个用户吗?')){
        this.deleteUser(user);
      }
    },
    deleteUser(user) {
      const index = this.users.findIndex(u => u.id === user.id);
      if (index !== -1) {
        this.users.splice(index, 1);
      }
    }
  },
  name: 'page2'
}
</script>
<style scoped>
.user-management {
  padding: 20px;
}
.user-management h2{
  margin-bottom: 20px;
}
.user-management table {
  width: 100%;
  border-collapse: collapse;
}
.user-management th,
.user-management td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
.user-management th {
  background-color: #f2f2f2;
}
.user-management button{
  margin-right: 10px;
  padding: 5px 10px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.user-management button:hover{
  background-color: #45a049;
}
.user-management .error-message{
  color: red;
  margin-top: 10px;
}
table{
  margin-top: 20px;
}
.over{
  margin-top: 20px;
}
</style>